package com.greate.community.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Component
public class UploadFileUtil {

    @Value("${qiniu.accessKey}")
    private String accessKey;

    @Value("${qiniu.secretKey}")
    private String secretKey;

    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${qiniu.path}")
    private String bucketUrl;

    /**
     * 在七牛云上保存文件
     * 返回字符串
     *
     * @param file
     * @return
     */
    public String saveFile(MultipartFile file) throws IOException {

        //构造一个带指定Region对象的配置类,指定华南
        Configuration cfg = new Configuration(Zone.zone2());
        //生成上传凭证，然后准备上传
        UploadManager uploadManager = new UploadManager(cfg);
        //创建权限类似于token
        Auth auth = Auth.create(accessKey,secretKey);
        //生成一个上传的token
        String upToken = auth.uploadToken(bucket);

        int pos = file.getOriginalFilename().lastIndexOf(".");
        if (pos<0) {
            return null;
        }
        //生存文件名
        String fileExt = file.getOriginalFilename().substring(pos+1).toLowerCase();
        String fileName = UUID.randomUUID().toString().replaceAll("-","")+"."+fileExt;
        try {
            Response response = uploadManager.put(file.getBytes(), fileName, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(bucketUrl+putRet.key+"结果");
            return bucketUrl+"/"+putRet.key;

        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            return null;
        }
    }

    public String getFileSuffix(String fileName) {
        //获取文件后缀名
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

//    private void checkSuffix(MultipartFile file) {
//        String suffix = getFileSuffix(file.getOriginalFilename());
//        if (!Arrays.asList(allowSuffix).contains(suffix)) {
//            logger.error("不支持的文件类型");
//
//            throw new CustomRuntimeException(ResponseInfo.ResponseInfo_700.getCode().toString(), "不支持的文件类型");
//        }
//    }

}
